package org.d8s.magicapi.util;


import com.alibaba.fastjson.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.security.SecureRandom;
import java.util.Map;
import java.util.Random;
import java.util.TreeMap;

/**
 * @author 冰点
 * @date 2021-5-20 16:08:09
 * @since 1.1.1
 */
public class SecurityUtil {
    private static final Logger log = LoggerFactory.getLogger(SecurityUtil.class);
    private static final String SYMBOLS = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
    private static final Random RANDOM = new SecureRandom();
    private static final String DEFAULT_CHARSET = "UTF-8";


    /**
     * 生成签名
     *
     * @param params
     * @param appId
     * @param appSecret
     * @return
     * @throws Exception
     */
    public static String generateSign(Map<String, Object> params, String appId, String appSecret) throws Exception {
        String str = concatParams(params);
        String stringToSignTemp = URLEncoder.encode(appSecret, DEFAULT_CHARSET) + str + URLEncoder.encode(appSecret, DEFAULT_CHARSET);
        log.info("要加密的字符串stringToSignTemp=[{}]", stringToSignTemp);
        return Md5Util.md5(stringToSignTemp);
    }

    /**
     * 拼接参数对接方式1
     *
     * @param params
     * @return
     */
    public static String concatParams(Map<String, Object> params) {
        StringBuffer sb = new StringBuffer();
        params.forEach((key, value) -> {
            try {
                String val = String.valueOf(params.get(key));
                key = URLEncoder.encode(key, DEFAULT_CHARSET);
                val = URLEncoder.encode(val, DEFAULT_CHARSET);
                sb.append("&" + key + "=" + val);
            } catch (UnsupportedEncodingException e) {
                log.error("请求参数字符集不合法params:[{}]", JSON.toJSONString(params), e);
                return;
            }
        });
        return sb.toString().replaceFirst("&", "");
    }

    /**
     * 获取当前时间戳，单位秒
     *
     * @return
     */
    public static long getCurrentTimestamp() {
        return System.currentTimeMillis() / 1000;
    }

    /**
     * 获取当前时间戳，单位毫秒
     *
     * @return
     */
    public static long getCurrentTimestampMs() {
        return System.currentTimeMillis();
    }

    /**
     * 判断是否为基本类型
     *
     * @param obj
     * @return
     */
    private boolean isPrimitive(Object obj) {
        try {
            return obj.getClass().getDeclaredField("name").getType().isPrimitive();
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 校验签名
     *
     * @param
     * @return
     */
    public static void main(String[] args) {
        String token = "d27aaf52af26c0549de0ff11aa04595b";
        //组装参数
        Map<String, Object> map = new TreeMap<>();
        map.put("appId", "122");
        map.put("timestamp", "1623118238621");
        map.put("data","test");
        try {
            //生成签名
            String appId = "122";
            String appSecret = "123456";
            String result = generateSign(map, appId, appSecret);
            System.out.println("生成签名:" + result);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
